<template>
  <div class="analysis-page">


    <el-row :gutter="20">
      <!-- 输入区域 -->
      <el-col :span="12">
        <el-card class="input-card">
          <template #header>
            <div class="card-header">
              <span>输入文档内容</span>
              <div class="header-actions">
                <el-button type="primary" @click="analyze" :loading="analyzing" :disabled="!canAnalyze">需求分析</el-button>
                <el-button type="success" @click="generateCases" :loading="generatingCases" :disabled="!canAnalyze">用例生成</el-button>
              </div>
            </div>
          </template>

          <!-- 文件上传区域 -->
          <div class="upload-section">
            <el-upload
              ref="uploadRef"
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-exceed="handleFileExceed"
              :before-upload="beforeUpload"
              :before-remove="beforeRemove"
              :disabled="processingDocument"
              :show-file-list="false"
              :limit="1"
              accept=".pdf,.doc,.docx,.txt,.md,.html,.xls,.xlsx,.ppt,.pptx"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持 PDF、Word、Excel、PowerPoint、文本等格式，文件大小不超过 50MB
                </div>
              </template>
            </el-upload>
            
            <div v-if="selectedFile" class="file-info">
              <el-icon><Document /></el-icon>
              <span class="file-name">{{ selectedFile.name }}</span>
              <span class="file-size">({{ formatFileSize(selectedFile.size) }})</span>
              <span class="status-separator"></span>
              <div v-if="processingDocument" class="processing-status">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span>正在识别文档内容...</span>
              </div>
              <div v-else-if="documentProcessed" class="processed-status">
                <el-icon style="color: #67c23a"><SuccessFilled /></el-icon>
                <span>文档识别完成，内容已回写到文本框</span>
              </div>
            </div>
          </div>

          <!-- 文本输入区域 -->
          <div class="text-input-section">
            <el-input
              v-model="requirementText"
              type="textarea"
              :rows="14"
              placeholder="上传文件或输入需求内容后进行需求分析和用例生成"
              show-word-limit
              :maxlength="100000"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 结果区域 -->
      <el-col :span="12">
        <el-card class="result-card">
          <template #header>
            <div class="card-header">
              <span>分析结果</span>
              <div v-if="analysisResult" class="header-actions">
                <el-button 
                  type="primary" 
                  @click="togglePreviewMode"
                  :icon="previewMode ? 'Edit' : 'View'"
                  size="small"
                >
                  {{ previewMode ? '编辑' : '预览' }}
                </el-button>
                <el-button 
                  type="success" 
                  @click="saveResult"
                  :icon="'Check'"
                  size="small"
                  v-if="!previewMode"
                >
                  保存
                </el-button>
                <el-button 
                  type="success" 
                  @click="downloadResult"
                  :icon="'Download'"
                  size="small"
                >
                  下载
                </el-button>
              </div>
            </div>
          </template>

          <div v-if="analyzing" class="loading-container">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>AI正在分析中，请稍候...</p>
          </div>

          <div v-else-if="analysisResult" class="result-content">
            <!-- 预览模式 -->
            <div v-if="previewMode" class="result-preview" v-html="markdownToHtml(editableResult)"></div>
            <!-- 编辑模式 -->
            <div v-else class="result-editor">
              <el-input
                v-model="editableResult"
                type="textarea"
                :rows="20"
                placeholder="编辑Markdown内容..."
                class="markdown-editor"
              />
            </div>
          </div>

          <div v-else class="empty-result">
            <el-icon><TrendCharts /></el-icon>
            <p>请输入需求内容或上传文件，然后点击"开始分析"</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 历史记录 -->
    <div class="history-section mt-20">
      <el-row :gutter="20">
        <!-- 需求分析历史 -->
        <el-col :span="12">
          <el-card class="history-card">
            <template #header>
              <div class="history-header">
                <h4>需求分析历史</h4>
                <el-pagination
                  v-if="analysisHistory.total > 0"
                  :current-page="analysisHistory.currentPage"
                  :page-size="10"
                  :total="analysisHistory.total"
                  layout="prev, pager, next"
                  size="small"
                  @current-change="handleAnalysisPageChange"
                />
              </div>
            </template>
            
            <div class="history-list">
              <div
                v-for="record in analysisHistory.records"
                :key="record.id"
                class="history-item"
                @click="viewDetail(record)"
              >
                <div class="item-header">
                  <span class="file-name">{{ record.file_name || '文本输入' }}</span>
                  <el-tag :type="record.status === 'success' ? 'success' : 'danger'" size="small">
                    {{ record.status === 'success' ? '成功' : '失败' }}
                  </el-tag>
                </div>
                <div class="item-meta">
                  <span class="file-type">{{ record.file_type }}</span>
                  <span class="create-time">{{ formatTime(record.created_at) }}</span>
                </div>
              </div>
              
              <div v-if="analysisHistory.records.length === 0" class="empty-history">
                <el-icon><Document /></el-icon>
                <p>暂无需求分析记录</p>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 用例生成历史 -->
        <el-col :span="12">
          <el-card class="history-card">
            <template #header>
              <div class="history-header">
                <h4>用例生成历史</h4>
                <el-pagination
                  v-if="testCaseHistory.total > 0"
                  :current-page="testCaseHistory.currentPage"
                  :page-size="10"
                  :total="testCaseHistory.total"
                  layout="prev, pager, next"
                  size="small"
                  @current-change="handleTestCasePageChange"
                />
              </div>
            </template>
            
            <div class="history-list">
              <div
                v-for="record in testCaseHistory.records"
                :key="record.id"
                class="history-item"
                @click="viewDetail(record)"
              >
                <div class="item-header">
                  <span class="file-name">{{ record.file_name || '文本输入' }}</span>
                  <el-tag :type="record.status === 'success' ? 'success' : 'danger'" size="small">
                    {{ record.status === 'success' ? '成功' : '失败' }}
                  </el-tag>
                </div>
                <div class="item-meta">
                  <span class="file-type">{{ record.file_type }}</span>
                  <span class="create-time">{{ formatTime(record.created_at) }}</span>
                </div>
              </div>
              
              <div v-if="testCaseHistory.records.length === 0" class="empty-history">
                <el-icon><List /></el-icon>
                <p>暂无用例生成记录</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailDialog"
      :title="detailRecord?.analysis_type === 'requirement_analysis' ? '分析详情' : '生成详情'"
      width="65%"
      :close-on-click-modal="false"
      class="detail-dialog"
    >
      <div v-if="detailLoading" class="detail-loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        <p>加载详情中...</p>
      </div>
      
      <div v-else-if="detailRecord" class="detail-content">
        <el-descriptions :column="3" border size="small" class="detail-descriptions">
          <el-descriptions-item label="文件名" label-class-name="detail-label">
            <span class="detail-value">{{ detailRecord.file_name || '文本输入' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="类型" label-class-name="detail-label">
            <el-tag 
              :type="detailRecord.analysis_type === 'requirement_analysis' ? 'primary' : 'success'" 
              size="small"
            >
              {{ detailRecord.analysis_type === 'requirement_analysis' ? '需求分析' : '用例生成' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态" label-class-name="detail-label">
            <el-tag 
              :type="detailRecord.status === 'success' ? 'success' : 'danger'" 
              size="small"
              effect="dark"
            >
              {{ detailRecord.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="文件类型" label-class-name="detail-label">
            <el-tag type="info" size="small" effect="plain">
              {{ detailRecord.file_type?.toUpperCase() || 'TEXT' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="AI模型" label-class-name="detail-label">
            <span class="detail-value model-name">{{ detailRecord.ai_model || 'gpt-3.5-turbo' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="分析时间" label-class-name="detail-label">
            <span class="detail-value time-value">{{ formatTime(detailRecord.created_at) }}</span>
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="detailRecord.error_message" class="error-section">
          <h4>错误信息</h4>
          <el-alert type="error" :closable="false">
            {{ detailRecord.error_message }}
          </el-alert>
        </div>
        
        <div v-if="detailRecord.input_content" class="input-section">
          <div class="section-header">
            <el-icon class="section-icon" color="#409eff"><Document /></el-icon>
            <h4 class="section-title">输入文档</h4>
          </div>
          <el-input
            :model-value="detailRecord.input_content"
            type="textarea"
            :rows="6"
            readonly
            class="detail-textarea input-textarea"
          />
        </div>
        
        <div v-if="detailRecord.output_content" class="output-section">
          <div class="section-header">
            <el-icon class="section-icon" color="#67c23a"><SuccessFilled /></el-icon>
            <h4 class="section-title">结果</h4>
          </div>
          <el-input
            :model-value="detailRecord.output_content"
            type="textarea"
            :rows="12"
            readonly
            class="detail-textarea output-textarea"
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="detailDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useToast } from 'vue-toastification'
import dayjs from 'dayjs'
import { analysisApi } from '@/api/analysis'
import { Loading, SuccessFilled, Document, List } from '@element-plus/icons-vue'
import { marked } from 'marked'

const toast = useToast()

// 组件引用
const uploadRef = ref()

// 响应式数据
const requirementText = ref('')
const selectedFile = ref(null)
const analyzing = ref(false)
const generatingCases = ref(false)
const processingDocument = ref(false)
const documentProcessed = ref(false)
const analysisResult = ref('')
const editableResult = ref('')
const previewMode = ref(true)
const currentOperation = ref('') // 'analysis' 或 'testcases'
const currentRecordId = ref(null) // 当前正在编辑的记录ID

// 分离的历史记录数据
const analysisHistory = ref({
  records: [],
  currentPage: 1,
  total: 0
})

const testCaseHistory = ref({
  records: [],
  currentPage: 1,
  total: 0
})

// 移除文档处理控制器，改为简单的状态管理

// 计算属性 - 控制按钮是否可用
const canAnalyze = computed(() => {
  // 如果正在处理文档，不能点击按钮
  if (processingDocument.value) return false
  // 如果有文件但还没处理完成，不能点击按钮
  if (selectedFile.value && !documentProcessed.value) return false
  // 必须有文本内容才能分析
  return requirementText.value.trim().length > 0
})

// 文件选择处理
const handleFileChange = async (file) => {
  console.log('文件选择事件触发:', file.name)
  selectedFile.value = file
  documentProcessed.value = false
  
  // 立即开始处理文档
  await processDocumentContent()
}

// 处理文件超出限制（替换现有文件）
const handleFileExceed = async (files) => {
  // 如果正在处理文档，不允许上传新文件
  if (processingDocument.value) {
    toast.warning('文档正在处理中，请稍候再上传')
    return
  }
  
  console.log('文件超出限制，替换现有文件:', files[0].name)
  
  // 先清除现有文件
  uploadRef.value.clearFiles()
  
  // 等待DOM更新
  await new Promise(resolve => setTimeout(resolve, 50))
  
  // 手动创建文件对象并处理
  const newFile = files[0]
  const fileWrapper = {
    name: newFile.name,
    size: newFile.size,
    raw: newFile,
    uid: Date.now() + Math.random(),
    status: 'ready'
  }
  
  console.log('创建新文件包装器:', fileWrapper.name)
  
  // 重置状态并处理新文件
  selectedFile.value = fileWrapper
  documentProcessed.value = false
  
  // 立即开始处理文档
  await processDocumentContent()
}

// 文件移除前处理
const beforeRemove = () => {
  console.log('移除文件')
  selectedFile.value = null
  documentProcessed.value = false
  return true
}

// 处理文档内容
const processDocumentContent = async () => {
  if (!selectedFile.value) return
  
  // 如果正在处理文档，不允许重复处理
  if (processingDocument.value) {
    console.log('文档正在处理中，忽略新的处理请求')
    return
  }
  
  try {
    processingDocument.value = true
    
    // 创建FormData
    const formData = new FormData()
    formData.append('document_file', selectedFile.value.raw)
    
    console.log('开始处理文档:', selectedFile.value.name)
    
    // 调用文档处理接口
    const response = await analysisApi.processDocument(formData)
    
    console.log('收到响应:', response)
    
    if (response && response.data && response.data.success) {
      // 将识别结果回写到文本框
      requirementText.value = response.data.content
      documentProcessed.value = true
      
      toast.success(`文档识别成功！提取到 ${response.data.content.length} 个字符`)
      console.log('文档处理成功:', {
        filename: response.data.file_info?.filename,
        content_length: response.data.content.length,
        file_type: response.data.file_info?.file_type
      })
    } else {
      const errorMsg = response?.data?.error || response?.error || '文档处理失败'
      toast.error(errorMsg)
      console.error('文档处理失败:', errorMsg, response)
    }
  } catch (error) {
    console.error('文档处理异常:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status
    })
    
    let errorMsg = '文档处理失败'
    if (error.response?.data?.detail) {
      errorMsg += ': ' + error.response.data.detail
    } else if (error.message) {
      errorMsg += ': ' + error.message
    }
    
    toast.error(errorMsg)
  } finally {
    processingDocument.value = false
  }
}

// 文件上传前验证
const beforeUpload = (file) => {
  const allowedTypes = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'text/plain',
    'text/markdown',
    'text/html',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation'
  ]
  
  if (!allowedTypes.includes(file.type) && !file.name.match(/\.(pdf|doc|docx|txt|md|html|xls|xlsx|ppt|pptx)$/i)) {
    toast.error('不支持的文件类型')
    return false
  }
  
  if (file.size > 50 * 1024 * 1024) {
    toast.error('文件大小不能超过 50MB')
    return false
  }
  
  return true
}

// 分析需求
const analyze = async () => {
  if (!canAnalyze.value) {
    if (processingDocument.value) {
      toast.error('文档正在处理中，请稍候')
    } else if (selectedFile.value && !documentProcessed.value) {
      toast.error('请等待文档识别完成')
    } else {
      toast.error('请输入需求文本')
    }
    return
  }
  
  analyzing.value = true
  
  try {
    // 现在只使用文本输入，因为文档已经被处理并回写到文本框了
    const response = await analysisApi.analyzeText({
      requirement_text: requirementText.value
    })
    
    if (response && response.data) {
      // 修正字段名：使用 analysis 而不是 analysis_result
      analysisResult.value = response.data.analysis || response.data.error || '分析完成，但未返回结果'
      editableResult.value = analysisResult.value
      previewMode.value = true
      currentOperation.value = 'analysis'
      currentRecordId.value = response.data.record_id || null
      toast.success('分析完成')
      loadHistory()
    }
    
  } catch (error) {
    console.error('分析失败:', error)
    toast.error(error.response?.data?.detail || '分析失败，请重试')
  } finally {
    analyzing.value = false
  }
}

// 下载结果
const downloadResult = () => {
  const content = editableResult.value || analysisResult.value
  const blob = new Blob([content], { type: 'text/markdown' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  
  // 根据当前操作类型生成不同的文件名
  const timestamp = dayjs().format('YYYY-MM-DD_HH-mm-ss')
  const prefix = currentOperation.value === 'testcases' ? '用例生成' : '需求分析'
  a.download = `${prefix}_${timestamp}.md`
  
  a.click()
  URL.revokeObjectURL(url)
}

// 切换预览模式
const togglePreviewMode = () => {
  previewMode.value = !previewMode.value
}

// 配置marked选项
marked.setOptions({
  breaks: true,        // 换行符转换为<br>
  gfm: true,          // 启用GitHub风格的Markdown
  tables: true,       // 启用表格
  sanitize: false,    // 允许HTML标签
  smartypants: false  // 禁用智能标点符号
})

// Markdown转HTML
const markdownToHtml = (markdown) => {
  if (!markdown) return ''
  
  try {
    return marked(markdown)
  } catch (error) {
    console.error('Markdown渲染失败:', error)
    return markdown.replace(/\n/g, '<br>')
  }
}

// 保存结果
const saveResult = async () => {
  try {
    const timestamp = dayjs().format('YYYY-MM-DD_HH-mm-ss')
    const prefix = currentOperation.value === 'testcases' ? '用例生成' : '需求分析'
    
    const response = await analysisApi.saveAnalysis({
      content: editableResult.value,
      filename: `${prefix}_${timestamp}.md`,
      record_id: currentRecordId.value  // 传递记录ID
    })
    
    if (response && response.data && response.data.success) {
      toast.success('保存成功')
      loadHistory()  // 刷新历史记录
    } else {
      toast.error('保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    toast.error(error.response?.data?.detail || '保存失败，请重试')
  }
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) return `${size} B`
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`
  return `${(size / 1024 / 1024).toFixed(1)} MB`
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}





// 生成用例
const generateCases = async () => {
  if (!canAnalyze.value) {
    if (processingDocument.value) {
      toast.error('文档正在处理中，请稍候')
    } else if (selectedFile.value && !documentProcessed.value) {
      toast.error('请等待文档识别完成')
    } else {
      toast.error('请输入需求文本')
    }
    return
  }
  
  generatingCases.value = true
  
  try {
    // 现在只使用文本输入，因为文档已经被处理并回写到文本框了
    const response = await analysisApi.generateTestCases({
      requirement_text: requirementText.value
    })
    
    if (response && response.data) {
      analysisResult.value = response.data.test_cases || response.data.error || '测试用例生成完成，但未返回结果'
      editableResult.value = analysisResult.value
      previewMode.value = true
      currentOperation.value = 'testcases'
      currentRecordId.value = response.data.record_id || null
      toast.success('测试用例生成完成')
      loadHistory()
    }
    
  } catch (error) {
    console.error('测试用例生成失败:', error)
    toast.error(error.response?.data?.detail || '测试用例生成失败，请重试')
  } finally {
    generatingCases.value = false
  }
}

// 查看详情相关数据
const detailDialog = ref(false)
const detailRecord = ref(null)
const detailLoading = ref(false)

// 查看详情
const viewDetail = async (record) => {
  try {
    detailLoading.value = true
    detailDialog.value = true
    
    console.log('查看详情:', record)
    const response = await analysisApi.getDetail(record.id)
    
    if (response && response.data && response.data.success) {
      detailRecord.value = {
        ...record,
        ...response.data.record
      }
    } else {
      toast.error('获取详情失败')
      detailDialog.value = false
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    toast.error('获取详情失败')
    detailDialog.value = false
  } finally {
    detailLoading.value = false
  }
}

// 加载需求分析历史
const loadAnalysisHistory = async (page = 1) => {
  try {
    console.log('开始加载需求分析历史记录...')
    const response = await analysisApi.getHistory({
      page: page,
      page_size: 10,
      analysis_type: 'requirement_analysis'
    })
    console.log('需求分析历史响应:', response)
    
    if (response && response.data && response.data.success) {
      const records = response.data.records || []
      analysisHistory.value = {
        records: records,
        currentPage: page,
        total: response.data.pagination?.total || 0
      }
      console.log('加载到需求分析记录:', records.length, '条')
    }
  } catch (error) {
    console.error('加载需求分析历史失败:', error)
    toast.error('加载需求分析历史失败')
  }
}

// 加载用例生成历史
const loadTestCaseHistory = async (page = 1) => {
  try {
    console.log('开始加载用例生成历史记录...')
    const response = await analysisApi.getHistory({
      page: page,
      page_size: 10,
      analysis_type: 'test_case_generation'
    })
    console.log('用例生成历史响应:', response)
    
    if (response && response.data && response.data.success) {
      const records = response.data.records || []
      testCaseHistory.value = {
        records: records,
        currentPage: page,
        total: response.data.pagination?.total || 0
      }
      console.log('加载到用例生成记录:', records.length, '条')
    }
  } catch (error) {
    console.error('加载用例生成历史失败:', error)
    toast.error('加载用例生成历史失败')
  }
}

// 加载所有历史记录
const loadHistory = async () => {
  await Promise.all([
    loadAnalysisHistory(1),
    loadTestCaseHistory(1)
  ])
}

// 处理需求分析分页变化
const handleAnalysisPageChange = (page) => {
  loadAnalysisHistory(page)
}

// 处理用例生成分页变化
const handleTestCasePageChange = (page) => {
  loadTestCaseHistory(page)
}

onMounted(() => {
  loadHistory()
})
</script>

<style lang="scss" scoped>
.analysis-page {
  padding: 20px;
}

.input-card, .result-card {
  height: 600px;
  
  :deep(.el-card__header) {
    padding: 15px 20px;
    box-sizing: border-box;
    height: 56px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    height: 100%;
    
    .header-actions {
      display: flex;
      gap: 8px;
    }
  }
}

.upload-section {
  margin-bottom: 16px;
  
  .upload-demo {
    :deep(.el-upload) {
      width: 100%;
    }
    
    :deep(.el-upload-dragger) {
      width: 100%;
      height: 80px;
      padding: 12px;
    }
    
    :deep(.el-icon--upload) {
      font-size: 24px;
      margin-bottom: 8px;
    }
    
    :deep(.el-upload__text) {
      font-size: 13px;
      line-height: 1.4;
    }
    
    :deep(.el-upload__tip) {
      font-size: 12px;
      margin-top: 4px;
    }
  }
}

.text-input-section {
  .markdown-editor {
    :deep(.el-textarea__inner) {
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 14px;
      line-height: 1.5;
    }
  }
}

.file-info {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  margin-top: 10px;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 13px;
  
  .file-name {
    margin-left: 8px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
  }
  
  .file-size {
    margin-left: 8px;
    color: #999;
    font-size: 12px;
    flex-shrink: 0;
  }
  
  .status-separator {
    width: 1px;
    height: 16px;
    background-color: #e0e0e0;
    margin: 0 12px;
    flex-shrink: 0;
  }
}

.result-content {
  height: 500px;
  overflow-y: auto;
  
  .result-preview {
    line-height: 1.6;
    padding: 16px;
    font-size: 14px;
    color: #333;
    
    // 标题样式
    :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
      color: #2c3e50;
      margin-top: 24px;
      margin-bottom: 16px;
      font-weight: 600;
      line-height: 1.25;
    }
    
    :deep(h1) { 
      font-size: 32px; 
      border-bottom: 1px solid #eaecef;
      padding-bottom: 8px;
    }
    :deep(h2) { 
      font-size: 24px; 
      border-bottom: 1px solid #eaecef;
      padding-bottom: 8px;
    }
    :deep(h3) { font-size: 20px; }
    :deep(h4) { font-size: 16px; }
    :deep(h5) { font-size: 14px; }
    :deep(h6) { font-size: 13px; color: #6a737d; }
    
    // 段落
    :deep(p) {
      margin-bottom: 16px;
      margin-top: 0;
    }
    
    // 强调和斜体
    :deep(strong) {
      font-weight: 600;
    }
    
    :deep(em) {
      font-style: italic;
    }
    
    // 行内代码
    :deep(code) {
      background-color: rgba(27, 31, 35, 0.05);
      border-radius: 3px;
      font-size: 85%;
      margin: 0;
      padding: 0.2em 0.4em;
      font-family: 'SFMono-Regular', 'Consolas', 'Liberation Mono', 'Menlo', 'Courier', monospace;
    }
    
    // 代码块
    :deep(pre) {
      background-color: #f6f8fa;
      border-radius: 6px;
      font-size: 85%;
      line-height: 1.45;
      overflow: auto;
      padding: 16px;
      margin-bottom: 16px;
      
      code {
        background-color: transparent;
        border: 0;
        display: inline;
        line-height: inherit;
        margin: 0;
        overflow: visible;
        padding: 0;
        word-wrap: normal;
      }
    }
    
    // 列表
    :deep(ul), :deep(ol) {
      margin-bottom: 16px;
      margin-top: 0;
      padding-left: 2em;
    }
    
    :deep(li) {
      margin-bottom: 0.25em;
    }
    
    :deep(li > p) {
      margin-bottom: 0;
    }
    
    // 引用
    :deep(blockquote) {
      border-left: 0.25em solid #dfe2e5;
      color: #6a737d;
      margin: 0 0 16px 0;
      padding: 0 1em;
    }
    
    // 表格
    :deep(table) {
      border-collapse: collapse;
      border-spacing: 0;
      display: block;
      margin-bottom: 16px;
      overflow: auto;
      width: 100%;
      
      th, td {
        border: 1px solid #dfe2e5;
        padding: 6px 13px;
      }
      
      th {
        background-color: #f6f8fa;
        font-weight: 600;
      }
      
      tr:nth-child(2n) {
        background-color: #f6f8fa;
      }
    }
    
    // 分割线
    :deep(hr) {
      background-color: #e1e4e8;
      border: 0;
      height: 0.25em;
      margin: 24px 0;
      padding: 0;
    }
    
    // 链接
    :deep(a) {
      color: #0366d6;
      text-decoration: none;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }
  
  .result-editor {
    height: 100%;
    
    .markdown-editor {
      height: 100%;
      
      :deep(.el-textarea) {
        height: 100%;
      }
      
      :deep(.el-textarea__inner) {
        height: 100% !important;
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 14px;
        line-height: 1.5;
        resize: none;
      }
    }
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 500px;
  
  .el-icon {
    font-size: 48px;
    color: #409EFF;
    margin-bottom: 16px;
  }
  
  p {
    color: #666;
    font-size: 16px;
  }
}

.empty-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 500px;
  color: #999;
  
  .el-icon {
    font-size: 48px;
    margin-bottom: 16px;
  }
}

.history-card {
  margin-top: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.processing-status, .processed-status {
  display: flex;
  align-items: center;
  gap: 8px;
  border-radius: 4px;
  font-size: 13px;
  flex-shrink: 0;
  padding: 4px 8px;
}

.processing-status {
  background-color: #f0f9ff;
  color: #1890ff;
  border: 1px solid #d1ecf1;
}

.processed-status {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

// 历史记录样式
.history-section {
  .history-card {
    .history-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h4 {
        margin: 0;
        font-size: 14px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    .history-list {
      max-height: 400px;
      overflow-y: auto;
      
      .history-item {
        padding: 8px 12px;
        margin-bottom: 8px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s;
        font-size: 12px;
        
        &:hover {
          border-color: #409eff;
          background-color: #ecf5ff;
        }
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .item-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 4px;
          
          .file-name {
            font-weight: 500;
            color: #303133;
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-right: 8px;
          }
        }
        
        .item-meta {
          display: flex;
          justify-content: space-between;
          color: #909399;
          font-size: 11px;
          
          .file-type {
            text-transform: uppercase;
          }
        }
      }
      
      .empty-history {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 200px;
        color: #909399;
        
        .el-icon {
          font-size: 48px;
          margin-bottom: 12px;
        }
        
        p {
          margin: 0;
          font-size: 14px;
        }
      }
    }
  }
}

// 详情弹窗样式
.detail-dialog {
  :deep(.el-dialog__header) {
    padding: 16px 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    
    .el-dialog__title {
      color: white;
      font-weight: 600;
      font-size: 16px;
    }
    
    .el-dialog__headerbtn .el-dialog__close {
      color: white;
      font-size: 18px;
      
      &:hover {
        color: #f0f0f0;
      }
    }
  }
  
  :deep(.el-dialog__body) {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
  }
  
  :deep(.el-dialog__footer) {
    padding: 12px 20px;
    background-color: #fafafa;
    border-top: 1px solid #e4e7ed;
  }
}

.detail-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  
  .el-icon {
    font-size: 32px;
    margin-bottom: 12px;
    color: #409eff;
  }
  
  p {
    color: #606266;
    font-size: 14px;
  }
}

.detail-content {
  .detail-descriptions {
    :deep(.el-descriptions__label.detail-label) {
      background-color: #f8f9fa !important;
      color: #495057 !important;
      font-weight: 600 !important;
      font-size: 13px !important;
      width: 80px !important;
    }
    
    :deep(.el-descriptions__content) {
      padding: 8px 12px !important;
    }
    
    .detail-value {
      color: #303133;
      font-size: 13px;
      
      &.model-name {
        color: #409eff;
        font-weight: 500;
        font-family: 'Monaco', 'Consolas', monospace;
      }
      
      &.time-value {
        color: #909399;
        font-size: 12px;
      }
    }
  }
  
  .error-section {
    margin-top: 20px;
    
    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      color: #f56c6c;
      font-weight: 600;
    }
  }
  
  .input-section,
  .output-section {
    margin-top: 24px;
    
    .section-header {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      
      .section-icon {
        margin-right: 8px;
        font-size: 16px;
      }
      
      .section-title {
        margin: 0;
        font-size: 14px;
        font-weight: 600;
        color: #303133;
      }
    }
  }
  
  .detail-textarea {
    :deep(.el-textarea__inner) {
      font-family: 'SF Mono', 'Monaco', 'Consolas', 'Liberation Mono', 'Courier New', monospace;
      font-size: 12px;
      line-height: 1.5;
      border-radius: 6px;
      transition: all 0.3s;
      
      &:focus {
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }
    }
    
    &.input-textarea :deep(.el-textarea__inner) {
      background-color: #f8f9fa;
      border-color: #e9ecef;
      color: #14314e;
    }
    
    &.output-textarea :deep(.el-textarea__inner) {
      background-color: #ffffff;
      border-color: #c9d88c;
      color: #1a2bc4;
    }
  }
}
</style> 